package com.cloud.mall.log.error;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloud.mall.base.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @Autowired
    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法

	@Value("${spring.application.name}")
	private  String applicationName;
	@Value("${server.port}")
	private  String serverPort;
    @Value("${error.message.source}")
    private  String error;

	@ExceptionHandler(RuntimeException.class)
	public BaseResponse exceptionHandler(HttpServletRequest request, Exception ex) throws UnknownHostException{
		Map<String,String[]> parameterMap=request.getParameterMap();
		StackTraceElement[] stackTrace = ex.getStackTrace();
		StackTraceElement stackTraceElement = stackTrace[0];
		JSONObject jsonObject= JSON.parseObject(JSON.toJSONString(stackTraceElement));
		jsonObject.put("paramterContent",parameterMap);
		jsonObject.put("errorContent",ex.getMessage());
		jsonObject.put("serverId",applicationName);
		jsonObject.put("messageId",applicationName+ "-"+UUID.randomUUID().toString());
		jsonObject.put("createTime",new Date());
		jsonObject.put("ipaddr",getServerPort());
        jsonObject.put("error",error);
        sendmq(jsonObject);
		return BaseResponse.setResultError("系统错误!");
	}

	private String getServerPort() throws UnknownHostException {
		InetAddress ip =Inet4Address.getLocalHost();
		return  ip.getHostAddress()+":"+serverPort;
	}

	private  void sendmq(JSONObject jsonObject){
        rabbitTemplate.convertAndSend("logDirectExchange", "logDirectRouting", jsonObject.toString());
    }

}
